<?php

class Application_Helpers_ItemsLoader extends Zend_Controller_Action_Helper_Abstract
{
    const ACTIVE = 1;
    
	/**
	 * Database adapter
	 * @var Zend_Db_Adapter_Pdo_Mysql
	 */
	private $_db;

	/**
	 * Database table
	 * @var Zend_Db_Table_Abstract
	 */
	private $_dbTable;
	
	/**
	 * Model
	 * @var Application_Model_*
	 */
	private $_model;

	
	public function __construct()
	{
		$this->_db = Zend_Registry::get('db');
	}
	
	public function direct($model)
	{
		$this->setModel($model);
		$this->setTable($model->getTable());

		return $this;
	}

	public function setTable($table)
	{
		$this->_dbTable = $table;
	}
	
	public function getTable()
	{
		return $this->_dbTable;
	}
	
	public function setModel($model)
	{
		$this->_model = $model;
	}
	
	public function getModel()
	{
		return $this->_model;
	}
	
	/**
	 * Get item
	 * @param string $value
	 * @param string $key
	 * @throws Exception
	 */
    public function getItem($value, $key = 'id')
    {
    	$where = $this->_createWhere(array(
    		$key => $value
    	));
    	
        $item = $this->getTable()->fetchRow($where);

        if (!$item) {
            throw new Exception("Can't find item with ". $key ."=" . $value);
        }
        
        return $item;
    }

    /**
     * Get all rows.
     *
     * Honors the Zend_Db_Adapter fetch mode.
     *
     * @param string|array|Zend_Db_Table_Select $where  OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
     * @param string|array                      $order  OPTIONAL An SQL ORDER clause.
     * @param integer                           $count  OPTIONAL An SQL LIMIT count.
     * @param integer                           $offset OPTIONAL An SQL LIMIT offset.
     * @return stdClass
     */
    public function getList($fields = null, $order = null, $limit = null, $offset = null)
	{
    	$where = $this->_createWhere($fields);
    	$count = $this->getCount($where, $order);
    	$offset = ($offset > 1) ? $offset : null;
		$items = $this->getTable()->fetchAll($where, $order, $limit, $offset);

		if (!$items) {
            throw new Exception("Can't find items");
        }
		
        $data = new stdClass();
        $data->items = $items;
		$data->count = $count;
        
		return $data;
	}
	
	/**
	 * Get items count
	 * @param array $where
	 * @param string $order
	 */
	public function getCount($where = null, $order = null)
	{
		$select = $this->getTable()->select();
		$select->from($this->getTable(), array('count(*) as count'));
		
		if (count($where) > 0)
		{
			foreach ($where as $condition => $value)
			{
				$select->where($condition, $value);				
			}
		}
		
		$rows = $this->getTable()->fetchAll($select);

		return $rows[0]->count;       
	}
	
	/**
	 * Creating where clause
	 * @param array $fields
	 */
	private function _createWhere($fields = null)
	{
		$default = array(
			'active' => self::ACTIVE
		);
		
		$_where = array_merge((array)$default, (array)$fields);
		$where = array();
		
		foreach ($_where as $key => $value)
		{
			if (!is_int($key))
			{
				$key .= '=?'; 
			}
			
			$where[$key] = $value;
		}
		
		return $where;
	}
	
	/**
	 * Load page by page url
	 * @param string $pageUrl
	 */
	public function loadPage($pageUrl)
	{
		$pagesModel = new Application_Model_Pages();
		$helper = clone $this;
		
		try
		{
			$page = $pagesModel->getPage($helper, $pageUrl);			
		}
		catch(Exception $e)
    	{
			throw new Zend_Controller_Exception($e->getMessage());
    	}
		
		return $page; 
	}
	
	/**
	 * Set page
	 */
	public function setPageParameters($view, $page)
	{
		try
		{
	    	$indexPage = $this->loadPage('index');
    	}
		catch(Exception $e)
    	{
			throw new Zend_Controller_Exception($e->getMessage());
    	}

    	$title = $page->title;
    	$description = (!empty($page->description)) ? $page->description : $indexPage->description;
    	$keywords = (!empty($page->keywords)) ? $page->keywords : $indexPage->keywords;
    	
		$view->headTitle($title);
		$view->headMeta()->appendName('description', $description);
		$view->headMeta()->appendName('keywords', $keywords);
 
		return $view;
	}
}